const {
	db,
	dbCmd,
	$,
	result_success,
	result_error,
	appletInfoCollection,
	shopieCollection,
	userCollection
} = require('../../common/constants')
module.exports = async function(params = {}) {
	const token = this.getUniIdToken()
	if (!token) {
		return result_error('登录失效,请重新登录')
	}
	let payload = await this.uniID.checkToken(token)
	if (payload.code) {
		return payload
	}
	let cUser = await userCollection.doc(payload.uid).get()
	cUser = cUser.data[0]
	if(!cUser.app_id){
		return result_success({})
	}
	//获取当前应用
	let appletInfoData = await appletInfoCollection.doc(cUser.app_id).get()
	appletInfoData = appletInfoData.data[0]
	let cDate = new Date()
	if (cDate && cDate.toString().indexOf('UTC') > -1) {
		cDate.setHours(cDate.getHours() + 8)
	}
	let cYear = cDate.getFullYear();
	let cMonth = cDate.getMonth() + 1;
	let cDay = cDate.getDate();

	let sDate = cDate.setMonth(cDate.getMonth() - 6)
	sDate = new Date(sDate)

	let timezone = 8;
	let calDateTime = timezone * 60 * 60 * 1000;
	
	let queryShopieTotal = {
		app_id: appletInfoData._id,
		shop_id: appletInfoData._id,
		type: 0
	};

	let categories = []
	let seriesData = []
	let businessTotal = 0
	for (i = 0; i < 6; i++) {
		sDate = cDate.setMonth(cDate.getMonth() + 1)
		sDate = new Date(sDate)
		let sYear = sDate.getFullYear();
		let sMonth = sDate.getMonth() + 1;
		let sDay = sDate.getDate();
		let startDate = new Date(sYear + "-" + sMonth + '-1  00:00:00');
		let endDate = new Date(sYear + "-" + sMonth + '-31   23:59:59');
		let startDateTime;
		let endDateTime;
		if (startDate && startDate.toString().indexOf('UTC') > -1) {
			startDateTime = startDate.getTime() - calDateTime;
			endDateTime = endDate.getTime() - calDateTime;
		} else {
			startDateTime = startDate.getTime();
			endDateTime = endDate.getTime();
		}
		queryShopieTotal.create_time = dbCmd.gte(startDateTime).and(dbCmd.lte(endDateTime))
		let customerCount = await shopieCollection.aggregate().match(queryShopieTotal).group({
			_id: '$creator_id',
			count: $.sum(1)
		}).limit(1000).end();
		let total_count = customerCount.data.length

		if (total_count) {
			categories.push(sYear + "年" + sMonth + "月")
			seriesData.push(total_count)
		}
	}
	let rData = {
		"categories": categories,
		"series": [{
			"name": "",
			"data": seriesData
		}]
	}
	return result_success(rData)
}